<template>
  <div class="sell-car-page">
    <div class="container">
      <el-card class="sell-card">
        <template #header>
          <h2>发布卖车信息</h2>
          <p class="subtitle">填写车辆信息，快速找到买家</p>
        </template>

        <div class="sell-content">
          <el-form
            ref="formRef"
            :model="carForm"
            :rules="formRules"
            label-width="120px"
            class="sell-form"
            :disabled="submitting"
          >
            <!-- 基本信息 -->
            <el-form-item label="车辆品牌" prop="brand">
              <el-select v-model="carForm.brand" placeholder="选择品牌" @change="handleBrandChange">
                <el-option
                  v-for="brand in brandOptions"
                  :key="brand.value"
                  :label="brand.label"
                  :value="brand.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="车辆型号" prop="model">
              <el-select v-model="carForm.model" placeholder="选择型号" :disabled="!carForm.brand">
                <el-option
                  v-for="model in modelOptions"
                  :key="model.value"
                  :label="model.label"
                  :value="model.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="车辆标题" prop="title">
              <el-input v-model="carForm.title" placeholder="例如：2018款 大众朗逸 1.5L 自动舒适版" />
            </el-form-item>

            <el-form-item label="车辆描述" prop="description">
              <el-input
                v-model="carForm.description"
                type="textarea"
                :rows="4"
                placeholder="详细描述车辆状况、配置、保养情况等"
                maxlength="500"
                show-word-limit
              />
            </el-form-item>

            <!-- 车辆信息 -->
            <el-form-item label="上牌时间" prop="regDate">
              <el-date-picker
                v-model="carForm.regDate"
                type="month"
                placeholder="选择上牌时间"
                value-format="YYYY-MM"
              />
            </el-form-item>

            <el-form-item label="行驶里程" prop="distance">
              <el-input-number
                v-model="carForm.distance"
                :min="0"
                :max="100"
                :precision="1"
                controls-position="right"
              />
              <span class="unit">万公里</span>
            </el-form-item>

            <el-form-item label="变速箱" prop="gearbox">
              <el-radio-group v-model="carForm.gearbox">
                <el-radio label="manual">手动</el-radio>
                <el-radio label="auto">自动</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="排放标准" prop="emission">
              <el-select v-model="carForm.emission" placeholder="选择排放标准">
                <el-option label="国四" value="国四" />
                <el-option label="国五" value="国五" />
                <el-option label="国六" value="国六" />
              </el-select>
            </el-form-item>

            <el-form-item label="排量" prop="displacement">
              <el-input-number
                v-model="carForm.displacement"
                :min="0.8"
                :max="6.0"
                :step="0.1"
                :precision="1"
                controls-position="right"
              />
              <span class="unit">L</span>
            </el-form-item>

            <el-form-item label="车辆颜色" prop="color">
              <el-input v-model="carForm.color" placeholder="请输入车辆颜色" />
            </el-form-item>

            <!-- 价格信息 -->
            <el-form-item label="期望售价" prop="price">
              <el-input-number
                v-model="carForm.price"
                :min="1"
                :max="1000"
                :precision="2"
                controls-position="right"
              />
              <span class="unit">万元</span>
            </el-form-item>

            <el-form-item label="新车价格" prop="originalPrice">
              <el-input-number
                v-model="carForm.originalPrice"
                :min="1"
                :max="1000"
                :precision="2"
                controls-position="right"
              />
              <span class="unit">万元</span>
            </el-form-item>

            <!-- 车辆图片 -->
            <el-form-item label="车辆图片" prop="images">
              <el-upload
                v-model:file-list="carForm.images"
                action="/api/upload"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :on-success="handleUploadSuccess"
                :before-upload="beforeUpload"
                :limit="10"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
            </el-form-item>

            <!-- 联系方式 -->
            <el-form-item label="联系人" prop="contactName">
              <el-input v-model="carForm.contactName" placeholder="请输入联系人姓名" />
            </el-form-item>

            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="carForm.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>

            <el-form-item label="所在城市" prop="location">
              <el-input v-model="carForm.location" placeholder="例如：北京朝阳区" />
            </el-form-item>

            <!-- 提交按钮 -->
            <el-form-item>
              <el-button type="primary" size="large" @click="handleSubmit" :loading="submitting">
                发布车辆信息
              </el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 发布提示 -->
          <div class="publish-tips">
            <h3>发布提示</h3>
            <ul>
              <li>请确保填写的信息真实准确</li>
              <li>上传清晰、真实的车辆图片</li>
              <li>价格合理有助于快速成交</li>
              <li>发布后我们的工作人员会进行审核</li>
              <li>审核通过后车辆信息将展示在平台上</li>
            </ul>
          </div>
        </div>
      </el-card>

      <!-- 图片预览对话框 -->
      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Plus } from '@element-plus/icons-vue'
import { useCarStore } from '@/store/car'
import { ElMessage } from 'element-plus'

const router = useRouter()
const carStore = useCarStore()

const formRef = ref()
const submitting = ref(false)
const dialogVisible = ref(false)
const dialogImageUrl = ref('')

const carForm = reactive({
  brand: '',
  model: '',
  title: '',
  description: '',
  regDate: '',
  distance: 0,
  gearbox: '',
  emission: '',
  displacement: 0,
  color: '',
  price: 0,
  originalPrice: 0,
  images: [],
  contactName: '',
  contactPhone: '',
  location: ''
})

const brandOptions = [
  { label: '大众', value: 'volkswagen' },
  { label: '丰田', value: 'toyota' },
  { label: '本田', value: 'honda' },
  { label: '奔驰', value: 'benz' },
  { label: '宝马', value: 'bmw' },
  { label: '奥迪', value: 'audi' }
]

const modelOptions = computed(() => {
  const models = {
    volkswagen: [
      { label: '朗逸', value: 'lavida' },
      { label: '帕萨特', value: 'passat' },
      { label: '途观', value: 'tiguan' }
    ],
    toyota: [
      { label: '卡罗拉', value: 'corolla' },
      { label: '凯美瑞', value: 'camry' },
      { label: 'RAV4', value: 'rav4' }
    ],
    honda: [
      { label: '思域', value: 'civic' },
      { label: '雅阁', value: 'accord' },
      { label: 'CR-V', value: 'crv' }
    ]
  }
  return models[carForm.brand] || []
})

const formRules = {
  brand: [
    { required: true, message: '请选择车辆品牌', trigger: 'change' }
  ],
  model: [
    { required: true, message: '请选择车辆型号', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入车辆标题', trigger: 'blur' },
    { min: 5, max: 50, message: '标题长度在 5 到 50 个字符', trigger: 'blur' }
  ],
  regDate: [
    { required: true, message: '请选择上牌时间', trigger: 'change' }
  ],
  distance: [
    { required: true, message: '请输入行驶里程', trigger: 'blur' }
  ],
  gearbox: [
    { required: true, message: '请选择变速箱类型', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入期望售价', trigger: 'blur' }
  ],
  contactName: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  location: [
    { required: true, message: '请输入所在城市', trigger: 'blur' }
  ]
}

const handleBrandChange = () => {
  carForm.model = ''
}

const handleRemove = (file, fileList) => {
  carForm.images = fileList
}

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

const handleUploadSuccess = (response, file, fileList) => {
  carForm.images = fileList
}

const beforeUpload = (file) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isJPGOrPNG) {
    ElMessage.error('图片只能是 JPG/PNG 格式!')
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
  }

  return isJPGOrPNG && isLt5M
}

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    // 发布车辆
    await carStore.publishNewCar(carForm)
    
    ElMessage.success('发布成功，等待审核')
    router.push('/cars')
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error('发布失败: ' + error.message)
    }
  } finally {
    submitting.value = false
  }
}

const handleReset = () => {
  if (formRef.value) {
    formRef.value.resetFields()
    carForm.images = []
  }
}
</script>

<style lang="scss" scoped>
.sell-car-page {
  padding: 20px 0;

  .container {
    max-width: 800px;
    margin: 0 auto;
    padding: 0 20px;
  }
}

.sell-card {
  :deep(.el-card__header) {
    border-bottom: 1px solid #f0f0f0;
    padding: 20px;

    h2 {
      margin: 0 0 8px;
      font-size: 20px;
      color: #333;
    }

    .subtitle {
      margin: 0;
      color: #666;
      font-size: 14px;
    }
  }
}

.sell-content {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 40px;
  padding: 20px;
}

.sell-form {
  :deep(.el-form-item) {
    margin-bottom: 20px;
  }

  .unit {
    margin-left: 8px;
    color: #666;
  }
}

.publish-tips {
  h3 {
    margin: 0 0 16px;
    font-size: 16px;
    color: #333;
  }

  ul {
    margin: 0;
    padding-left: 20px;
    color: #666;
    line-height: 1.8;

    li {
      margin-bottom: 8px;
    }
  }
}

@media (max-width: 768px) {
  .sell-content {
    grid-template-columns: 1fr;
    gap: 30px;
    padding: 15px;
  }

  .sell-form {
    :deep(.el-form-item) {
      .el-form-item__label {
        width: 100px !important;
      }
    }
  }
}
</style>